package com.up.cloudfeiyibackend.service.impl;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.annotations.Until;
import com.up.cloudfeiyibackend.constant.EventMessageConstant;
import com.up.cloudfeiyibackend.constant.UserMessageConstant;
import com.up.cloudfeiyibackend.dto.*;
import com.up.cloudfeiyibackend.entity.*;
import com.up.cloudfeiyibackend.mapper.EventMapper;
import com.up.cloudfeiyibackend.mapper.InheritorMapper;
import com.up.cloudfeiyibackend.mapper.UserMapper;
import com.up.cloudfeiyibackend.result.PageResult;
import com.up.cloudfeiyibackend.result.Result;
import com.up.cloudfeiyibackend.service.EventService;
import com.up.cloudfeiyibackend.service.UserService;
import com.up.cloudfeiyibackend.util.UserHolder;
import com.up.cloudfeiyibackend.vo.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class EventServiceImpl implements EventService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private InheritorMapper inheritorMapper;


    /**
     * 分页查询所有非遗活动
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<EventVO> page(EventPageDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<Event> events = eventMapper.page(dto);

        List<EventVO> eventVOList = new ArrayList<>();
        for (Event e : events) {
            EventVO vo = new EventVO();
            BeanUtils.copyProperties(e, vo);
            eventVOList.add(vo);
        }

        Page<Event> page = (Page<Event>) events;
        return new PageResult<>(page.getTotal(), eventVOList);
    }

    /**
     * 获取所有活动分类
     *
     * @return
     */
    @Override
    public List<EventCategoryVO> getEventCategory() {
        List<EventCategoryVO> eventCategoryList = eventMapper.getEventCategory();
        return eventCategoryList;
    }


    /**
     * 根据分类ID获取活动数量
     *
     * @param categoryId
     * @return
     */
    @Override
    public Integer getEventCountByCategory(Long categoryId) {
        Integer countByCategory = eventMapper.getEventCountByCategory(categoryId);
        return countByCategory;
    }

    /**
     * 查询指定活动详情
     *
     * @param eventId
     * @return
     */
    @Override
    public EventDetailVO getEventDetail(Long eventId) {
        Event event = eventMapper.getEventById(eventId);
        EventDetail result = eventMapper.getEventDetail(eventId);
        EventDetailVO eventDetailVO = new EventDetailVO();
        BeanUtils.copyProperties(event, eventDetailVO);
        eventDetailVO.setDescription(result.getDescription());
        // 处理图片和视频字段
        if (result.getImages() != null && !result.getImages().isEmpty()) {
            eventDetailVO.setImages(JSONUtil.toList(result.getImages(), String.class));
        }
        if (result.getVideos() != null && !result.getVideos().isEmpty()) {
            eventDetailVO.setVideos(JSONUtil.toList(result.getVideos(), String.class));
        }
        return eventDetailVO;
    }


    /**
     * 报名活动
     *
     * @param
     * @return
     */
    @Override
    public Result signUp(EventSignupDto eventSignupDto) {
        // 判断活动是否存在
        Event event = eventMapper.getEvent(eventSignupDto.getEventId());
        if (event == null) {
            return Result.error("活动不存在");
        }
        Long userId = UserHolder.get();
        if (userId == null) {
            return Result.error("请先登录");
        }
        EventSignup eventSignup = eventMapper.getSignUp(eventSignupDto.getEventId(), userId);
        if (eventSignup != null) {
            return Result.error("您已经报名过该活动");
        }
        eventSignupDto.setUserId(userId);
        eventMapper.signUp(eventSignupDto);
        return Result.success(EventMessageConstant.SIGN_UP_SUCCESS);
    }

    /**
     * 查询报名活动以及状态
     *
     * @return
     */
    @Override
    public Result<List<EventSignupStatusVO>> getEventSignupStatus() {
        Long userId = UserHolder.get();
        //查询该用户报名的所有活动
        List<EventSignup> eventSignups = eventMapper.getSignUps(userId);
        if (eventSignups == null || eventSignups.isEmpty()) {
            return Result.success(EventMessageConstant.NO_EVENT_SIGN_UP);
        }
        //查询所有活动信息
        //把所有活动id集合起来
        List<Long> eventIds = new ArrayList<>();
        for (EventSignup eventSignup : eventSignups) {
            eventIds.add(eventSignup.getEventId());
        }
        //根据活动id集合查询所有活动信息
        List<Event> events = eventMapper.getUserSignUps(eventIds);
        //把所有活动信息和报名状态封装成EventSignupStatusV0
        List<EventSignupStatusVO> eventSignupStatusV0List = new ArrayList<>();
        //通过比较活动id来匹配报名状态
        // 先构建活动ID到报名状态的映射
        Map<Long, Integer> statusMap = new HashMap<>();
        for (EventSignup signup : eventSignups) {
            statusMap.put(signup.getEventId(), signup.getStatus());
        }

        // 再遍历活动列表，直接从Map获取状态
        for (Event event : events) {
            EventSignupStatusVO vo = new EventSignupStatusVO();
            BeanUtils.copyProperties(event, vo);
            //通过event获取该event的报名状态
            Integer status = statusMap.get(event.getId());
            vo.setStatus(status);  // 直接获取，无需循环
            eventSignupStatusV0List.add(vo);
        }
        return Result.success(EventMessageConstant.EVENT_MESSAGE, eventSignupStatusV0List);
    }

    /**
     * 查询所有地区列表
     *
     * @return
     */
    @Override
    public Result<List<EventRegionVO>> getEventRegions() {
        List<EventRegionVO> eventRegionList = eventMapper.getEventRegions();
        return Result.success(EventMessageConstant.EVENT_MESSAGE, eventRegionList);
    }

    /**
     * 添加活动评论
     *
     * @param eventCommentsDto
     * @return
     */

    @Override
    public Result addEventComment(EventCommentsDto eventCommentsDto) {
        // 对象属性拷贝，将commentDTO中的属性值拷贝到comment对象中
        EventComment eventComment = new EventComment();
        BeanUtils.copyProperties(eventCommentsDto, eventComment);

        //判断是否为顶级评论
        EventComment parentComment = null;
        if (eventComment.getParentId() == null) {
            eventComment.setParentId(null);
            eventComment.setTopId(null);
        } else {
            // 新增评论为子评论
            // 判断父评论是否为顶级评论
            parentComment = eventMapper.getEventCommentByCommentId(eventComment.getParentId());
            if (parentComment.getTopId() != null) {
                // 父评论也是子评论，记录父评论的topId作为当前评论的topId
                eventComment.setTopId(parentComment.getTopId());
            } else {
                // 父评论是顶级评论，记录父评论的commentId作为当前评论的topId
                eventComment.setTopId(parentComment.getCommentId());
            }
        }
        // 获取当前登录用户的ID和用户名，作为新增评论数据实体类的属性值
        Long userId = UserHolder.get();
        User user = userMapper.findById(userId);

        // 设置实体类对象的属性
        eventComment.setUserId(userId);
        eventComment.setCreateBy(user.getUsername());


        // 新增评论
        eventMapper.addEventComment(eventComment);
        return Result.success(EventMessageConstant.EVENT_COMMENT_SUCCESS);
    }


    /**
     * 删除评论
     *
     * @param eventCommentId
     * @return
     */
    @Override
    public Result deleteEventComment(Long eventCommentId) {
        //获取当前用户的ID
        Long userId = UserHolder.get();
        //判断该评论是否属于当前用户
        EventComment eventComment = eventMapper.getEventCommentByCommentById(eventCommentId);
        if (!eventComment.getUserId().equals(userId)) {
            return Result.error("您没有权限删除该评论");
        }
        //删除评论
        //顶级评论，删除所有子评论
        if (eventComment.getParentId() == null) {
            eventMapper.deleteAllChildren(eventCommentId);

        } else {
            // 子评论，只需要更新状态即可
            eventMapper.deleteEventComment(eventCommentId);
        }
        return Result.success(EventMessageConstant.DELETE_EVENT_COMMENT_SUCCESS);
    }


    /**
     * 展示活动顶级评论
     *
     * @param eventId
     * @return
     */
    @Override
    public Result<List<EventCommentsVO>> getAllEventTopComment(Long eventId) {
        List<EventCommentsVO> eventCommentsVOS = eventMapper.getAllEventTopComment(eventId);
        return Result.success(EventMessageConstant.EVENT_MESSAGE, eventCommentsVOS);
    }


    /**
     * 展示活动评论的回复
     *
     * @param eventCommentsReplyDto
     * @return
     */
    @Override
    public Result<List<EventCommentsReplyVO>> listReplysByEventId(EventCommentsReplyDto eventCommentsReplyDto) {
        // topID作为查询条件，查询回复评论列表
        Long topId = eventCommentsReplyDto.getTopId();
        // parentID作为查询条件，查询回复关系
        Long parentId = eventCommentsReplyDto.getParentId();

        List<EventCommentsReplyVO> eventCommentsReplyVOS = eventMapper.listReplysByEventId(topId, parentId);


        return Result.success(EventMessageConstant.EVENT_MESSAGE, eventCommentsReplyVOS);
    }


    /**
     * 非遗传承人发布活动
     *
     * @param eventApplicationDto
     * @return
     */
    @Override
    public Result EventApplication(EventApplicationDto eventApplicationDto) {
        //判断当前用户是否为非遗传承人
        Long userId = UserHolder.get();
        Inheritor inheritor = userMapper.isInherit(userId);
        if (inheritor == null)
            {
                return Result.error(UserMessageConstant.NO_INHERITOR);
            }else {

            eventApplicationDto.setUserId(userId);
            EventApplication eventApplication = new EventApplication();
            BeanUtils.copyProperties(eventApplicationDto, eventApplication);
            // 处理图片和视频字段
            List<String> detailImages = eventApplicationDto.getDetailImages();
            if (detailImages != null && !detailImages.isEmpty()) {
                try {
                    String s = objectMapper.writeValueAsString(detailImages);
                    eventApplication.setDetailImages(s);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
            eventMapper.EventApplication(eventApplication);
            return Result.success(EventMessageConstant.EVENT_APPLICATION_SUCCESS);
        }

    }


    /**
     *
     * 获取当前用户所申请的活动申请表
     * @return
     */
    @Override
    public Result<List<EventApplicationVO>> getAllEventApplication() {
        Long userId = UserHolder.get();
        List<EventApplication> eventApplications = eventMapper.getAllEventApplication(userId);
        if (eventApplications == null || eventApplications.isEmpty()){
            return Result.error(EventMessageConstant.NO_EVENT_APPLICATION);
        }
        List<EventApplicationVO> eventApplicationVOS = new ArrayList<>();
        for (EventApplication eventApplication : eventApplications) {
            EventApplicationVO eventApplicationVO = new EventApplicationVO();
            BeanUtils.copyProperties(eventApplication, eventApplicationVO);
            // 处理图片和视频字段
            if (eventApplication.getDetailImages() != null && !eventApplication.getDetailImages().isEmpty()) {
                try {
                    List<String> detailImages = JSONUtil.toList(eventApplication.getDetailImages(), String.class);
                    eventApplicationVO.setDetailImages(detailImages);
                }
                catch (Exception e) {
                throw new RuntimeException(e);}
            }
            Long categoryId = eventApplication.getCategoryId();
            Long regionId = eventApplication.getRegionId();
            //将分类id和区域id转换成名称
            String eventCategory = eventMapper.getEventCategoryById(categoryId);
            String eventRegion = eventMapper.getEventRegionById(regionId);
            Inheritor myInheritor = inheritorMapper.getMyInheritor(userId);
            eventApplicationVO.setCategoryName(eventCategory);
            eventApplicationVO.setRegionName(eventRegion);
            eventApplicationVO.setUserName(myInheritor.getRealName());
            eventApplicationVOS.add(eventApplicationVO);
        }
        return Result.success(EventMessageConstant.EVENT_MESSAGE, eventApplicationVOS);
    }


    /**
     *
     * 获取回复当前用户评论中未被用户查看的总数
     * @return
     */
    @Override
    public Result<Integer> getNovIEWCommentCount() {
        Long userId = UserHolder.get();
        //获得所有父id是当前用户的评论的id的评论id
        List<Long> commentIds = eventMapper.getCommentIdsByUserId(userId);
        Integer NoViewCount = commentIds.size();
        return Result.success(EventMessageConstant.EVENT_MESSAGE, NoViewCount);
    }


    /**
     *
     * 获取所有回复当前用户评论的评论
     * @return
     */
    @Override
    public Result<List<ReplyCommentNotificationVO>> getNoViewCommentNotification() {
        Long userId = UserHolder.get();
        //获取所有回复当前用户评论的评论
        List<EventComment> commentIds = eventMapper.getAllCommentIdsByUserId(userId);
        List<ReplyCommentNotificationVO> replyCommentNotificationVOS = new ArrayList<>();
        List<Long> commentIdList = commentIds.stream().map(EventComment::getCommentId).toList();
        for (EventComment eventComment : commentIds) {

            ReplyCommentNotificationVO replyCommentNotificationVO = new ReplyCommentNotificationVO();

            //获取评论的用户名
            User user = userMapper.findById(eventComment.getUserId());
            replyCommentNotificationVO.setCommentContent(eventComment.getContent());
            replyCommentNotificationVO.setCommentId(eventComment.getCommentId());
            replyCommentNotificationVO.setCreateTime(eventComment.getCreateTime());
            replyCommentNotificationVO.setCreatUserNickname(user.getNickname());
            replyCommentNotificationVO.setCommentUserAvatar(user.getAvatarUrl());
            replyCommentNotificationVO.setEventId(eventComment.getEventId());
            replyCommentNotificationVO.setTopId(eventComment.getTopId());
            //获取活动图片
            Event event = eventMapper.getEventById(eventComment.getEventId());
            replyCommentNotificationVO.setEventImage(event.getImage());
            replyCommentNotificationVOS.add(replyCommentNotificationVO);
        }
        //修改这些评论的浏览状态

        eventMapper.updateCommentStatus(commentIdList);
        return Result.success(EventMessageConstant.EVENT_MESSAGE, replyCommentNotificationVOS);
    }

}





